// customlineedit.cpp
#include "customlineedit.h"
#include <QMouseEvent>
#include <QShowEvent>
#include <QTimer>
#include <QHBoxLayout>

CustomLineEdit::CustomLineEdit(QWidget *parent)
    : QLineEdit(parent)
{
    // 设置为只读，防止键盘自动弹出
    setReadOnly(true);
}

void CustomLineEdit::mousePressEvent(QMouseEvent *event)
{
    // 点击时显示全屏输入框
    showFullScreenInput();

    // 调用父类实现
    QLineEdit::mousePressEvent(event);
}

void CustomLineEdit::keyPressEvent(QKeyEvent *event)
{
    // 屏蔽所有键盘输入，因为设为只读了
    // 可以根据需要添加特定的快捷键处理
    QLineEdit::keyPressEvent(event);
}

void CustomLineEdit::showFullScreenInput()
{
    m_isFullScreenInputActive = true;
    FullScreenInputDialog dialog(text());
    dialog.setWindowModality(Qt::WindowModal);
    if (dialog.exec() == QDialog::Accepted)
    {
        setText(dialog.text());
    }

    m_isFullScreenInputActive = false;
}

// FullScreenInputDialog implementation
CustomLineEdit::FullScreenInputDialog::FullScreenInputDialog(const QString &text, QWidget *parent)
    : QDialog(parent)
{
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
    setModal(true);

    // 设置全屏
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();
    setGeometry(screenGeometry);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    // 设置布局间距和边距
    mainLayout->setSpacing(0);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    m_lineEdit = new QLineEdit(text);
    m_lineEdit->setAlignment(Qt::AlignCenter);
    m_lineEdit->setStyleSheet("font-size: 24px; padding: 20px;");

    // 创建按钮布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->setSpacing(20);
    buttonLayout->setContentsMargins(0, 0, 0, 0);

    QPushButton *confirmButton = new QPushButton("确认");
    confirmButton->setStyleSheet("font-size: 24px; padding: 10px;");

    QPushButton *cancelButton = new QPushButton("取消");
    cancelButton->setStyleSheet("font-size: 24px; padding: 10px;");

    // 左侧确认，右侧取消
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(cancelButton);

    // 修改布局方式，使输入框在顶部，按钮在底部
    mainLayout->addWidget(m_lineEdit, 0, Qt::AlignTop);
    mainLayout->addStretch();
    mainLayout->addLayout(buttonLayout, 0);

    // 连接按钮信号
    connect(confirmButton, &QPushButton::clicked, this, &QDialog::accept);
    connect(cancelButton, &QPushButton::clicked, this, &QDialog::reject);

    m_lineEdit->selectAll();
}

QString CustomLineEdit::FullScreenInputDialog::text() const
{
    return m_lineEdit->text();
}

void CustomLineEdit::FullScreenInputDialog::showEvent(QShowEvent *event)
{
    QDialog::showEvent(event);
    // 延迟设置焦点，确保窗口完全显示后再激活键盘
    QTimer::singleShot(100, [this]()
                       {
        m_lineEdit->setFocus();
        m_lineEdit->activateWindow(); });
}